from rest_framework import serializers
from .models import Category

class CategorySerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField(read_only=True)
    books_count = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Category
        fields = ['id', 'name', 'description', 'parent', 'children', 'books_count', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

    def get_children(self, obj):
        """获取子分类"""
        children = Category.objects.filter(parent=obj)
        return CategorySerializer(children, many=True).data

    def get_books_count(self, obj):
        """获取该分类下的图书数量"""
        return obj.books.count()

    def validate(self, data):
        """验证分类数据"""
        parent = data.get('parent')
        if parent and parent.id == self.instance.id:
            raise serializers.ValidationError("父分类不能是分类本身")
        return data
